package com.sc.weixin.member;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sc.dal.dto.member.AgentDto;
import com.sc.dal.dto.member.MemberNewsDto;
import com.sc.dal.dto.member.NewsTypeDto;
import com.sc.dal.dto.order.OrderDetailDto;
import com.sc.dal.model.ParamMap;
import com.sc.dal.model.article.Article;
import com.sc.dal.model.cart.Cart;
import com.sc.dal.model.member.Agent;
import com.sc.dal.model.member.Captcha;
import com.sc.dal.model.member.Member;
import com.sc.dal.model.member.MemberGrade;
import com.sc.dal.model.order.Products;
import com.sc.service.article.ArticleService;
import com.sc.service.cart.CartService;
import com.sc.service.member.AgentService;
import com.sc.service.member.CaptchaService;
import com.sc.service.member.MemberGradeService;
import com.sc.service.member.MemberNewsService;
import com.sc.service.member.MemberService;
import com.sc.service.order.OrderService;
import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.data.Common;
import com.sc.util.data.CookieUtils;
import com.sc.util.data.DataUtil;
import com.sc.util.data.DateUtil;
import com.sc.util.data.FileUtil;
import com.sc.util.data.MD5Util;
import com.sc.util.data.SessionContainer;
import com.sc.util.exception.ExceptionEnum;
/**
 * 
 * <h1>app用户表现层</h1> 
 * 
 * @author xujunbao 
 * @version MemberController.java,v0.1 2017年3月3日 下午5:21:57 xujunbao Exp  
 *
 */
@RequestMapping(value="/member")
@Controller
public class WXMemberController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**引入用户业务层*/
	@Autowired
	private MemberService memberService;
	/**引入验证码的业务层*/
	@Autowired
	private CaptchaService captchaService;		
	/**引入代理商等级的业务层*/
	@Autowired
	private MemberGradeService memberGradeService;
	/**引入代理商的业务层*/
	@Autowired
	private AgentService agentService;
	/**引入购物车的业务层*/
	@Autowired
	private CartService cartService;
	
	@Autowired
	private MemberNewsService memberNewsService;
	/** 引入订单业务层表 */
	@Autowired
	private OrderService orderService;	
	/**引入订单的业务层 (与商城动态共用表) */
	@Autowired
	private ArticleService articleService;
	@Autowired
	private EhCacheCacheManager factory;

	//消息中心
	@RequestMapping(value="/news")
	public String news(){
		return "/member/news";
	}
	//消息中心（物流）
	@RequestMapping(value="/newsCenter")
	public String newsCenter(){
		return "/member/newsCenter";
	}
	//通知消息
	@RequestMapping(value="/systemNotification")
	public String systemNotification(){
		return "/member/systemNotification";
	}
	//我的问答
	@RequestMapping(value="/myQuestion")
	public String myQuestion(){
		return "/member/myQuestion";
	}
	//物流消息
	@RequestMapping(value="/information")
	public String information(MemberNewsDto dto,Model model){
		model.addAttribute("dto", dto);
		return "/member/information";
	}
	/**
	 * 
	 * @Title:  aboutus
	 * @Description 根据商品会员id获取用户消息类别列表和各个类别的最新消息列表
	 * @param   article 
	 * @date    2017年6月21日下午14:24:05
	 * @author  LiuHuiXiang 
	 * @return  Map<String, Object> 返回类型
	 */
	
	@RequestMapping(value="/aboutUs")
	@ResponseBody
	public Object aboutUs(){
		ModelAndView mav = new ModelAndView("about/about_us");
		try{
			Article article = new Article();
			article.setAtype("9");
			List<Article> articleList = articleService.selectByParam(article);
			if(articleList!=null && articleList.size()>0){
				mav.addObject("article", articleList.get(0));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return mav;
	}
	
	
	/**
	 * @Title: newsList
	 * @Description 根据会员id获取用户消息类别列表和各个类别的最新消息列表
	 * @param mId
	 * @date 2017年4月14日下午15:08:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="/newsTypeList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> newsList(String mId){
		Map<String, Object> resultMap=new HashMap<String, Object>();
		try{
			if(Common.isEmpty(mId)){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
    			return resultMap;
			}
		    List<NewsTypeDto>	newsTypeDtoList = memberNewsService.selectMemberNewsTypeListByMid(mId);
		    resultMap.put("data", newsTypeDtoList);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_FAIL);
		}
		return resultMap;
		
	}	
	/**
	 * @Title: newsDtoList
	 * @Description 根据消息类别和用户Id获取对应类别的消息信息列表
	 * @param type
	 * @param mId
	 * @date 2017年4月14日下午15:08:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="/newsDtoList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> newsDtoList(String type,String mId){
		Map<String, Object> resultMap=new HashMap<String, Object>();
		try{
			if(Common.isEmpty(mId) || Common.isEmpty(type)){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
    			return resultMap;
			}
		    List<MemberNewsDto>	memberNewsDtoList = memberNewsService.selectMemberNews(type,mId);
		    if(memberNewsDtoList != null && memberNewsDtoList.size() >0){
		    	for(MemberNewsDto dto : memberNewsDtoList){
		    		String orderId = dto.getOrderId();
		    		//查找订单中的第一个商品
		    		OrderDetailDto detailDto = orderService.selectOrderDetailByOrderId(orderId);
		    		if(dto !=null){
		    			List<Products> products = detailDto.getProducts();
		    			if(products != null && products.size() >0){
		    				dto.setLatestOrderGgoodsName(products.get(0).getProductName());
		    				String imgUrl = products.get(0).getImgUrl();
							String imgUrl_new = "";
							if(Common.isNotEmpty(imgUrl)){
								String[] urls = imgUrl.split(";");
								for(String url:urls){
									imgUrl_new += ConfigBeanAdapter.fileAccessAddress + url +",";
								}
								dto.setLatestOrderGoodsImgUrl(imgUrl_new);
							}
							if(Common.isNotEmpty(products.get(0).getPicture() )){
								dto.setLatestOrderGoodsPicture(ConfigBeanAdapter.fileAccessAddress + products.get(0).getPicture() ); 
							}
		    			}

		    			dto.setExpressCode(detailDto.getExpressCode());
		    			dto.setExpressName(detailDto.getExpressName());
		    		}
		    	}
		    }
		    resultMap.put("data", memberNewsDtoList);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_FAIL);
		}
		return resultMap;
		
	}	
	/**跳转到首页*/
	@RequestMapping("/index")
	public String index(){
		return "/index";
	}
	/**跳转到登陆页面*/
	@RequestMapping("/loginPre")
	public String loginPre(String redirect ,HttpServletRequest request){
		request.setAttribute("redirect", redirect);
		return "/member/log";
	}
	
	/**跳转到个人信息页面*/
	@RequestMapping(value="/vip_safe_setting")
	public String vip_safe_setting(){
		return "/member/vip_safe_setting";
	}
	/**跳转到个人资料页面*/
	@RequestMapping(value="/personalData")
	public String vip_data_setting(){
		return "/member/personalData";
	}
	/**跳转到头像设置页面*/
	@RequestMapping(value="/vip_set_header")
	public String vip_set_header(){
		return "/member/vip_set_header";
	}
	/**跳转到用户地址信息页面*/
	@RequestMapping(value="/vip_set_address")
	public String vip_set_address(){
		return "/member/maAdress";
	}
	/**跳转到我的收藏页面*/
	@RequestMapping(value="/my_collection")
	public String my_collection(){
		return "member/my_collection";
	}
	/**跳转到修改密码页面*/
	@RequestMapping(value="/modify_psw")
	public String modify_psw(){
		return "member/modifyPassword";
	}
	
	/**跳转到修改昵称页面*/
	@RequestMapping(value="/modify")
	public String modify(){
		return "member/modify";
	}
	/**跳转到申请代理页面*/
	@RequestMapping(value="/agentApplication")
	public String agentApplication(){
		return "member/agentApplication";
	}
	/**
	 * 
	 * <h2>用户注册验证手机号</h2> 
	 * 
	 * @param mPhone 手机号
	 * @param code 验证码
	 * @param request
	 * @return
	 * @return ModelAndView  0:验证码错误；1：验证码已过期；2：未发送验证码
	 * @throws
	 */
	@RequestMapping(value="/register",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> register(String mPhone,String code,HttpServletRequest request ){
		Map<String, Object> resultMap=new HashMap<String, Object>();
		Member member = null;
		try {
			member=memberService.selectByPhone(mPhone);
			if(member!=null){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_USER_EXIST);
				return resultMap;
			}else{
				Cache levelOneCache = factory.getCache("smsVerificationCode");
				ValueWrapper c = levelOneCache.get(mPhone);
				if(c!=null){
					String getCode = c.get().toString();
					if(code!=null && code.equals(getCode)){
						DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
						resultMap.put("mPhone", mPhone);
						return resultMap;
					}else{
						DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CAPTCHA_ERROR);
						return resultMap;
					}
				}else{
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CAPTCHA_OUTTIME);
					return resultMap;
				}
			}
		} catch (Exception e) {
			logger.error("查询t_captcha表出现异常,通过手机号查询:"+mPhone,e);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CAPTCHA_NOT_EXIST);
		return resultMap;
	}
	/**
	 * 
	 * <h2>app用户注册添加密码</h2> 
	 * 
	 * @param sex
	 * @param mPwd
	 * @param request
	 * @return
	 * @return Map<String,Object> 
	 * @throws
	 */
	@RequestMapping(value="/register2",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> register2(String mPhone,String mPwd,HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> resultMap=new HashMap<String, Object>();
		Member member=new Member();
		try {
			member.setmPhone(mPhone);
			member.setmName(mPhone);
			member.setmPwd(MD5Util.MD5(mPwd));
			member.setCreateTime(new Date());
			memberService.insertSelective(member);
		} catch (Exception e) {
			logger.error("添加用户异常"+member.getmPhone(),e);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
		}
		try {
			member=memberService.selectByPhone(member.getmPhone());
		} catch (Exception e) {
			logger.error("通过电话查询刚添加的用户信息异常"+member.getmPhone(),e);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		long time=new Date().getTime();
		DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		member.setmPwd("");
		resultMap.put("time", time);
		resultMap.put("token", MD5Util.MD5(""+member.getmId()+time+ConfigBeanAdapter.privateKey));
		resultMap.put("data", member);
		return resultMap;	
	}
	/**
	 * 
	 * <h2>用户登陆</h2> 
	 * 
	 * @param uName
	 * @param uPwd
	 * @param request
	 * @return
	 * @return ModelAndView 
	 * @throws
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> login(String mPhone,String mPwd,HttpServletRequest request,HttpServletResponse response){
		//sesionID
		String SID = request.getSession().getId();
		Map<String, Object> resultMap=new HashMap<String, Object>();
		AgentDto member=null;
		try {
			member=memberService.selectAgentDtoByPhone(mPhone);
		} catch (Exception e) {
			logger.error("通过用户名查询刚添加的用户信息异常"+mPhone,e);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		if(member!=null){
			if(member.getmPwd().equals(MD5Util.MD5(mPwd))){
				long time=new Date().getTime();
				String token=MD5Util.MD5(""+member.getmId()+time+ConfigBeanAdapter.privateKey);
//				member.setmImg(ConfigBeanAdapter.fileAccessAddress+member.getmImg());
				member.setmPwd("");
				member.setmPaypwd("");
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
				request.getSession().setAttribute(token,member);
				if(member.getBirthday()!=null){
					member.setBirthdayStr(DateUtil.formatYMDToString(member.getBirthday()));
				}
				String memberInfo=CookieUtils.entityToString(member);
				resultMap.put("time", time);
				resultMap.put("token", token);
				resultMap.put("data", member);
				//将登录用户信息添加到session中和cookie中
				request.getSession().setAttribute(SessionContainer.sessionID + SID, member);
				CookieUtils.setCookie(request, response, SessionContainer.MEMBER_INFO, memberInfo,true);
				// 将用户购物车表中的信息调出到session和cookie中
				Cart cart = new Cart();
				cart.setMemberId(member.getmId());
				int count = cartService.count(cart);
				//购物车中的商品数量
				request.getSession().setAttribute(SessionContainer.myCartProductCount + SID,
						count);
				CookieUtils.setCookie(request, response, SessionContainer.myCartProductCount, count+"");
				return resultMap;
			}else{
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_USER_PWD_ERROR);
				return resultMap;
			}
		}else{
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_USER_NOT_REGISTER);
			return resultMap;
		}
	}
	/**
	 * 
	 * <h2>app修改密码接口</h2> 
	 * 
	 * @param oldPwd 原密码
	 * @param newPwd 新密码
	 * @param mId 用户id 
	 * @return
	 * @return Map<String,Object> 
	 * @throws
	 */
	@RequestMapping(value="/updatePwd",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updatePwd(String oldPwd,String newPwd,String mId){
		Map<String, Object> resultMap=new HashMap<String, Object>();
		Member member=null;
		try {
			member=memberService.selectByPrimaryKey(mId);
			if(member==null){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_USER_NOT_REGISTER);
				return resultMap;
			}else if(member.getmPwd().equals(MD5Util.MD5(oldPwd))){
				member.setmPwd(MD5Util.MD5(newPwd));
				memberService.updateByPrimaryKeySelective(member);
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			}else{
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_USER_OLD_PWD_ERROR);
				return resultMap;
			}
		} catch (Exception e) {
			logger.error("修改用户密码时异常",e);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_UPDATE);
		}
		return resultMap;
	}
	/**
	 * 
	 * <h2>app找回密码是验证</h2> 
	 * 
	 * @param code 验证码
	 * @param mPhone 手机号
	 * @return
	 * @return Map<String,Object> 
	 * @throws
	 */
	@RequestMapping(value="/findPwd",method=RequestMethod.POST)
	@ResponseBody
	//@SystemLog(module="接口",methods="找回密码")
	public Map<String, Object> findPwd(String mPhone,String mPwd,String code){
		Map<String, Object> resultMap=new HashMap<String, Object>();
		Member member=null;
		try {
			if(Common.isEmpty(mPhone)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			if(Common.isEmpty(code)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CAPTCHA_NOT_EXIST);
				return resultMap;
			}
			if(Common.isEmpty(mPwd)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_USER_PWD_NULL);
				return resultMap;
			}
			member=memberService.selectByPhone(mPhone);   
			if(member==null){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_USER_NOT_REGISTER);
				return resultMap;
			}else{
				Cache levelOneCache = factory.getCache("smsVerificationCode");
				ValueWrapper c = levelOneCache.get(mPhone);
				if(c!=null){
					String getCode = c.get().toString();
					if(code!=null && code.equals(getCode)){
						DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
						resultMap.put("mPhone", mPhone);
						/****修改密码**************/
						member.setmPwd(MD5Util.MD5(mPwd));
						memberService.updateByPrimaryKeySelective(member);
						return resultMap;
					}else{
						DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CAPTCHA_ERROR);
						return resultMap;
					}
				}else{
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CAPTCHA_OUTTIME);
					return resultMap;
				}
			}
		} catch (Exception e) {
			logger.error("查询数据库异常",e);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		return resultMap;
	}
	/**
	 * 
	 * <h2>修改个人资料</h2> 
	 * 
	 * @param request
	 * @param mId 用户的id
	 * @return.
	 * @return Map<String,Object> 
	 * @throws
	 */
	@RequestMapping(value="/upMemberInfo",method=RequestMethod.POST)
	@ResponseBody
	public String upMemberInfo(HttpServletRequest request,HttpServletResponse response,Member member){
		try {
			String SID = request.getSession().getId();
			AgentDto agentDto=new AgentDto();
			if(!Common.isEmpty(member.getBirthdayStr())){
				member.setBirthday(DateUtil.formatyMd(member.getBirthdayStr()));
			}
			member.setModifyTime(new Date());
			int flag=memberService.updateByPrimaryKeySelective(member);
			if(flag==1){			
				agentDto=memberService.selectAgentDtoByPhone(member.getmPhone());
			}
			if(agentDto.getmImg()==null){
				agentDto.setmImg(ConfigBeanAdapter.fileAccessAddress+agentDto.getmImg());
			}
			if(agentDto.getBirthday()!=null){
				agentDto.setBirthdayStr(DateUtil.formatYMDToString(agentDto.getBirthday()));
			}
			String memberInfo=CookieUtils.entityToString(agentDto);
			CookieUtils.setCookie(request, response,SessionContainer.MEMBER_INFO, memberInfo,true);
			request.getSession().setAttribute(SessionContainer.MEMBER_INFO + SID, agentDto);
			return "/member/vip_data_setting";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/member/vip_data_setting";
	}
	/***
	 * @date 2017.6.30修改  下列方法暂停使用
	 * xiongyong  
	 * 微信-上传个人图像
	 * @param mImg
	 * @param mId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/uploadmImg")
	public String uploadmImg(MultipartFile imageFiles,MultipartFile mImgPic,String mId,HttpServletRequest request,HttpServletResponse response){
		String imgUrl="";
		String matchPath="memberhead";
		Member member=new Member();
//		AgentDto agentDto=new AgentDto();
		try {
//			String SID = request.getSession().getId();
			if(imageFiles!=null){
				imgUrl=FileUtil.uploadByFile(imageFiles, "",matchPath , ConfigBeanAdapter.fileSaveAddress);
			}else{
				imgUrl=FileUtil.uploadByFile(mImgPic, "",matchPath , ConfigBeanAdapter.fileSaveAddress);
			}
			if(imgUrl!=null&&!"".equals(imgUrl)&&!"1".equals(imgUrl)&&!"2".equals(imgUrl)){				
				member.setmImg(imgUrl);
			}else{
				return "/member/vip_set_header";
			}
			member.setmId(mId);
			member.setModifyTime(new Date());
			int flag=memberService.updateByPrimaryKeySelective(member);
			if(flag > 0){			
//				agentDto=memberService.selectAgentDtoByPhone(member.getmPhone());
				return "/member/vip_set_header";
			}
			/*agentDto.setmImg(ConfigBeanAdapter.fileAccessAddress+agentDto.getmImg());
			if(member.getBirthday()!=null){
				agentDto.setBirthdayStr(DateUtil.formatYMDToString(agentDto.getBirthday()));
			}
			String memberInfo=CookieUtils.entityToString(agentDto);
			CookieUtils.setCookie(request, response, SessionContainer.MEMBER_INFO, memberInfo,true);
			request.getSession().setAttribute(SessionContainer.MEMBER_INFO + SID, agentDto);
			return "/member/vip_set_header";*/
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "/member/vip_set_header";
	}
	
	@RequestMapping(value="/exit")
	@ResponseBody
	public Map<String, Object> exit(HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> resultMap=new HashMap<String, Object>();
		try {
			String SID = request.getSession().getId();
			//删除cookie中的用户信息
			CookieUtils.setCookie(request, response, SessionContainer.MEMBER_INFO, null,true);
			//清楚session中的用户信息
			request.getSession().removeAttribute(SessionContainer.sessionID + SID);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			return resultMap;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_USER_EXIT_ERROR);
			return resultMap;
		}
	}
	@RequestMapping(value="/skip")
	@ResponseBody
	public Map<String, Object> skip(){
		Map<String, Object> resultMap=new HashMap<String, Object>();
		DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		return resultMap;
	}
	
	
	/**
	 * date: 2017.7.15变更 xiongyong
	 *  1、获取所用的代理商等级
	 *  2、判断当前用户是否登录，如登录则获取个人代理商信息
	 * <h2>方法注释说明</h2> 
	 * 
	 * @return
	 * @return Map<String,Object> 
	 * @throws
	 */
	@RequestMapping(value="/selectAllGrade")
	@ResponseBody
	public Map<String, Object> selectAllGrade(HttpServletRequest request, Integer agentGrade){
		Map<String, Object> resultMap=new HashMap<String, Object>();
		try {
			if(agentGrade==null){
				agentGrade=0;
			}
			List<MemberGrade> gradeList=memberGradeService.selectList();
			for (int i = 0; i < gradeList.size(); i++) {
				MemberGrade memberGrade=gradeList.get(i);
				if(memberGrade.getGrade()<agentGrade){
					gradeList.remove(i);
					i--;
				}
			}
			Member member = SessionContainer.getSessionMember(request);
			AgentDto memberDto=null;
			if(member!=null){
				String mPhone = member.getmPhone();
				if(Common.isNotEmpty(mPhone)){
					memberDto=memberService.selectAgentDtoByPhone(mPhone);
					resultMap.put("memberDto", memberDto);
				}
			}else{
				resultMap.put("memberDto", "null");
			}
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS, gradeList);
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		return resultMap;
	}
	/**
	 * 申请代理商的接口
	 * <h2>方法注释说明</h2> 
	 * 
	 * @param agentImg
	 * @param param
	 * @return
	 * @return Map<String,Object> 
	 * @throws
	 */
	@RequestMapping(value="/insertAgent")
	@ResponseBody
	public Map<String, Object> insertAgent(MultipartFile agentImg,HttpServletRequest request){
		Map<String, Object> resultMap=new HashMap<String, Object>();
		try {
			Agent agent=new Agent();
			String mId=request.getParameter("mId");
			String companyName=request.getParameter("companyName");
			String linkman=request.getParameter("linkman");
			String phone=request.getParameter("phone");
			String agentGrade=request.getParameter("agentGrade");
			agent.setmId(mId);
			agent.setCompanyName(companyName);
			agent.setLinkman(linkman);
			agent.setPhone(phone);
			agent.setAgentGrade(Integer.parseInt(agentGrade));
			String folder="businessLicence/";
			Member member=memberService.selectByPrimaryKey(agent.getmId());
			String businessLicence=FileUtil.uploadByFile(agentImg, "agentImg", folder, ConfigBeanAdapter.fileSaveAddress);
			if(businessLicence==null){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_FILE_ERROR);
				return resultMap;
			}else if("1".equals(businessLicence)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_FILE_NOT_EXIST);
				return resultMap;
			}else if("2".equals(businessLicence)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_FILE_fORMAT_ERROR);
				return resultMap;
			}
			if(member==null){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_USER_NOT_REGISTER);
				return resultMap;
			}
			ParamMap paramMap=new ParamMap();
			paramMap.put("reviewStatus", 0);
			List<AgentDto> agentList=agentService.selectList(paramMap);
			//如果已存在待审核的申请则修改申请信息
			if(agentList.size()>=1){
				agent.setId(agentList.get(0).getId());
				agent.setBusinessLicence(businessLicence);
				agent.setReviewStatus("0");
				agent.setCreateTime(new Date());
				agentService.updateAgent(agent);
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
				resultMap.put("msg", "申请已提交，等待审核");
				return resultMap;
			}
			agent.setBusinessLicence(businessLicence);
			agent.setCreateTime(new Date());
			agentService.insertAgent(agent);
			resultMap.put("msg", "申请已提交，等待审核");
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS,businessLicence);
		} catch (Exception e) {
			e.printStackTrace();
			
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		return resultMap;
	}
//	/**
//	 * 
//	 * <h2>验证通过，找回密码</h2> 
//	 * 
//	 * @param mId 用户的id
//	 * @param newPwd 新的密码
//	 * @return
//	 * @return Map<String,Object> 
//	 * @throws
//	 */
//	@RequestMapping("/findPwd")
//	@ResponseBody
//	public Map<String, Object> findPwd(Long mId,String newPwd){
//		Map<String, Object> resultMap=new HashMap<String, Object>();
//		Member member=null;
//		try {
//			member=memberService.selectByPrimaryKey(mId);
//			if(member!=null){
//				member.setMpwd(MD5Util.MD5(newPwd));
//				memberService.updateByPrimaryKeySelective(member);
//				resultMap.put("result", "1");
//				resultMap.put("msg", "密码已更改");
//				return resultMap;
//			}else{
//				resultMap.put("result", "0");
//				resultMap.put("msg", "用户不存在");
//				return resultMap;
//			}
//		} catch (Exception e) {
//			logger.error("根据id修改密码时异常：id="+mId,e);
//			resultMapUtils.handleResultMap(resultMap, ExceptionEnum.resultMap_SELECT);
//		}
//		return resultMap;
//	}
	
	
	
	/*****
	 * 获取用户个人信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/personalData",method=RequestMethod.POST)
	@ResponseBody
	public Object personalData(HttpServletRequest request,HttpServletResponse response){
		Member member = SessionContainer.getSessionMember(request);
		if(member == null){
			logger.warn("用户没有登录");
			return "/member/loginPre";
		}
		Map<String, Object> resultMap=new HashMap<String, Object>();
		try {
			member=memberService.selectByPrimaryKey(member.getmId());
		} catch (Exception e) {
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		return member;
	}
}
